//
//  CornerSection.m
//  Racing
//
//  Created by vy phan on 4/13/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CornerSection.h"


@implementation CornerSection
-(id) initWithLeft:(bool)isLeft_ Top:(BOOL)isTop_ X:(int)x Y:(int)y
{
//	super( x, y );
//	this.left = left;
//	this.top = top;
//	if ( left ) 
//		corner_x = x;
//	else
//		corner_x = x + getBounds().width;
//	
//	if ( top )
//		corner_y = y;
//	else
//		corner_y = y + getBounds().height;
	self = [super initWithX:x Y:y];
	self->top = isTop_;
	self->left = isLeft_;
	self->type = CORNER;

	if (self->left) 
		self->corner_x = x;
	else 
		self->corner_x = x + [([self getBounds]) width];
	
	
	if ( self->top )
		self->corner_y = y;
	else
		self->corner_y = y + [([self getBounds]) height];
	
	return self;
}

-(bool) toLeft
{
	return self->left;
}

-(bool) toTop
{
	return self->top;
}

-(int) cornerX
{
	return self->corner_x;
}

-(int) cornerY
{
	return self->corner_y;
}

-(int) type
{
	return CORNER;
}

-(BOOL) intersects:(Vehicle*)vehicle State:(State*)state
{
	Rectangle* bounds = [self getBounds];
	for ( int i = 0; i < state->numpoints; i++ ) {
		float x = [[state->xpoints objectAtIndex:i] floatValue];
		float y = [[state->ypoints objectAtIndex:i] floatValue];
		if ( [bounds contains:(int)x Y:(int)y] ) {
			return YES;
		}
	}
	return NO;
}

-(void) checkCollision:(Vehicle*)vehicle State:(State*)state
{
	Rectangle *bounds = [self getBounds];
	for ( int i = 0; i < state->numpoints; i++ ) {
		float x = [[state->xpoints objectAtIndex:i] floatValue];
		float y = [[state->ypoints objectAtIndex:i] floatValue];
		
		float rx = x - corner_x;
		float ry = y - corner_y;
		
		//if ( !bounds.contains( (int)x, (int)y ) )
		//
		if ( top && y < [bounds y] )
			continue;
		if ( !top && y > [bounds y] + [bounds height] )
			continue;
		if ( left && x < [bounds x] )
			continue;
		if ( !left && x > [bounds x] + [bounds width] )
			continue;
		
		float distSq = rx*rx + ry*ry;
		if ( distSq > [bounds width] * [bounds width] ) {
			float dist = sqrtf( distSq );
			rx /= dist;
			ry /= dist;
			[state collide:x Y:y NX:-rx NY:-ry];//.collide( x, y, -rx, -ry );
		}
	}
}

-(float) distanceToEnd:(Vehicle*)vehicle{
	Section *next = [self getNextSection];
	Rectangle *bounds = [next getBounds];
	BOOL horiz = [bounds x] != [([self getBounds]) x];
	State *state = [vehicle currentState];
	if ( horiz ) {
		float dist = corner_x - state->x;
		if ( dist < 0 ) dist = -dist;
		return dist;
	}
	else {
		float dist = corner_y - state->y;
		if ( dist < 0 ) dist = -dist;
		return dist;
	}	
}
@end
